package com.gcxy.utils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.nio.charset.Charset;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @author WangZhixian
 * @description 加密/解密工具类
 * @date 2021/4/27
 */
public class EncryptUtil {

    static final String DECISION_ENGINE_SALT = "欢迎使用智风控平台";

    static final String ALGORITHM = "AES";

    static Charset charset = Charset.forName("UTF-8");

//    /**
//     * 加密算法
//     *
//     * @param content
//     * @return byte[]
//     * @author wangzhixian
//     * @date 2021/04/27
//     */
//    public static byte[] encrypt(String content) throws NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException, InvalidKeyException, IOException {
//        SecretKey secretKey = generateKey();
//        byte[] contentBytes = encryptByAes(content, secretKey);
//        byte[][] saltHalfBytes = ByteUtil.subHalfByte(secretKey.getEncoded());
//        //加盐、将密钥分两段放入内容字节数组中
//        byte[] secondEncodedByte = Base64.getEncoder().encode(ByteUtil.mergeByteByStream(DECISION_ENGINE_SALT.getBytes(charset),saltHalfBytes[0], contentBytes,saltHalfBytes[1]));
//        return secondEncodedByte;
//    }
//
//    /**
//     * 解密算法
//     *
//     * @param data
//     * @return byte[]
//     * @author wangzhixian
//     * @date 2021/04/27
//     */
//    public static String decrypt(byte[] data) throws IOException, IllegalBlockSizeException, NoSuchPaddingException, BadPaddingException, NoSuchAlgorithmException, InvalidKeyException {
//        byte[] decode = Base64.getDecoder().decode(data);
//        int saltLength = DECISION_ENGINE_SALT.getBytes("UTF-8").length;
//        //获取加密后的内容字节数组
//        byte[] encrypt = ByteUtil.subByte(decode, saltLength + 8, decode.length - saltLength - 16);
//        //拼接获取密钥字节数组,生成密钥
//        byte[] keyBytesBefore = ByteUtil.subByte(decode, saltLength, 8);
//        byte[] keyBytesBehind = ByteUtil.subByte(decode, decode.length - 8, 8);
//        byte[] keyBytes = ByteUtil.byteMerger(keyBytesBefore, keyBytesBehind);
//        SecretKey newKey = new SecretKeySpec(keyBytes, ALGORITHM);
//        return decryptByAes(encrypt,newKey);
//    }
//
//    /**
//     * 生成AES密钥
//     *
//     * @return javax.crypto.SecretKey
//     * @author wangzhixian
//     * @date 2021/04/27
//     */
//    public static SecretKey generateKey() throws NoSuchAlgorithmException {
//        KeyGenerator secretGenerator = KeyGenerator.getInstance(ALGORITHM);
//        SecureRandom secureRandom = new SecureRandom();
//        secretGenerator.init(secureRandom);
//        SecretKey secretKey = secretGenerator.generateKey();
//        return secretKey;
//    }
//
//    /**
//     * AES加密算法
//     *
//     * @param content 需要加密的内容
//	 * @param secretKey 密钥
//     * @return byte[]
//     * @author wangzhixian
//     * @date 2021/04/27
//     */
//    public static byte[] encryptByAes(String content, SecretKey secretKey) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { // 加密
//        return aes(content.getBytes(charset),Cipher.ENCRYPT_MODE,secretKey);
//    }
//
//    /**
//     * AES解密算法
//     *
//     * @param contentArray 需解密的字节数组
//	 * @param secretKey 密钥
//     * @return java.lang.String
//     * @author wangzhixian
//     * @date 2021/04/27
//     */
//    public static String decryptByAes(byte[] contentArray, SecretKey secretKey) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { // 解密
//        byte[] result =  aes(contentArray,Cipher.DECRYPT_MODE,secretKey);
//        return new String(result,charset);
//    }
//
//    private static byte[] aes(byte[] contentArray, int mode, SecretKey secretKey)
//            throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
//        Cipher cipher = Cipher.getInstance(ALGORITHM);
//        cipher.init(mode, secretKey);
//        byte[] result = cipher.doFinal(contentArray);
//        return result;
//    }

    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 128;

    /**
     * 获取密钥对
     *
     * @return 密钥对
     */
    public static KeyPair getKeyPair() throws Exception {
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(1024);
        return generator.generateKeyPair();
    }

    /**
     * 获取私钥
     *
     * @param privateKey 私钥字符串
     * @return
     */
    public static PrivateKey getPrivateKey(String privateKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.decodeBase64(privateKey.getBytes());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
        return keyFactory.generatePrivate(keySpec);
    }

    /**
     * 获取公钥
     *
     * @param publicKey 公钥字符串
     * @return
     */
    public static PublicKey getPublicKey(String publicKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.decodeBase64(publicKey.getBytes());
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
        return keyFactory.generatePublic(keySpec);
    }

    /**
     * RSA加密
     *
     * @param data 待加密数据
     * @return
     */
    public static String encrypt(String data) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, getKeyPair().getPublic());
        int inputLen = data.getBytes().length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offset > 0) {
            if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        // 获取加密内容使用base64进行编码,并以UTF-8为标准转化成字符串
        // 加密后的字符串
        return new String(Base64.encodeBase64String(encryptedData));
    }

    /**
     * RSA解密
     *
     * @param data 待解密数据
     * @return
     */
    public static String decrypt(String data) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, getKeyPair().getPrivate());
        byte[] dataBytes = Base64.decodeBase64(data);
        int inputLen = dataBytes.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offset > 0) {
            if (inputLen - offset > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(dataBytes, offset, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        // 解密后的内容
        return new String(decryptedData, "UTF-8");
    }

    /**
     * 签名
     *
     * @param data 待签名数据
     * @param privateKey 私钥
     * @return 签名
     */
    public static String sign(String data, PrivateKey privateKey) throws Exception {
        byte[] keyBytes = privateKey.getEncoded();
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey key = keyFactory.generatePrivate(keySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initSign(key);
        signature.update(data.getBytes());
        return new String(Base64.encodeBase64(signature.sign()));
    }

    /**
     * 验签
     *
     * @param srcData 原始字符串
     * @param publicKey 公钥
     * @param sign 签名
     * @return 是否验签通过
     */
    public static boolean verify(String srcData, PublicKey publicKey, String sign) throws Exception {
        byte[] keyBytes = publicKey.getEncoded();
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey key = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initVerify(key);
        signature.update(srcData.getBytes());
        return signature.verify(Base64.decodeBase64(sign.getBytes()));
    }



}
